using SmartCommunity.WebApi.Services.System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace SmartCommunity.WebApi.Controllers.System
{
    /// <summary>
    /// API接口：用户
    /// </summary>
    [ApiController]
    [Authorize(Roles = "admin")]
    [Route("api/system/[controller]")]
    public class UserController : BaseController
    {
        #region 构造函数
        private readonly UserService userService;
        public UserController(UserService userService)
        {
            this.userService = userService;
        }
        #endregion

        #region 查询导出 
        /// <summary>
        /// 分页查询
        /// </summary>
        [HttpGet]
        public async Task<PageResult<UserDto>> GetList([FromQuery] UserQuery query, [FromQuery] Pager pager)
        {
            return await userService.FindPagedList(query, pager, CurrentUser);
        }

        /// <summary>
        /// 通过主键查询
        /// </summary>
        /// <param name="id">主键ID</param>
        [HttpGet("{id}")]
        public async Task<UserDto> GetOne(int id)
        {
            return await userService.FindUserById(id);
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        [HttpGet("export")]
        public async Task<ActionResult> ExportExcel([FromQuery] UserQuery query)
        {
            var pageData = await userService.FindPagedList(query, Pager.Unpaged, CurrentUser);
            var exporter = new ExcelExporter();
            exporter.AddTitleRow(0, "用户名", "昵称", "手机号码", "电子邮箱", "性别", "用户状态", "创建人", "创建时间");
            int rowIndex = 1;
            foreach (var dto in pageData.DataList)
            {
                exporter.AddDataRow(rowIndex++, 0, dto.Username, dto.Nickname, dto.Cellphone, dto.Email, dto.GenderName, dto.StatusName, dto.CreatedBy, dto.CreatedTime);
            }
            var bytes = exporter.GetExcelData();
            return File(bytes, CONTENT_TYPE_EXCEL, $"用户导出{DateTime.Now:yyyyMMddHHmmss}.xlsx");
        }
        #endregion

        #region 增 删 改
        /// <summary>
        /// 新增用户
        /// </summary>
        [HttpPost]
        [Log("新增用户", OperateType.Create, false, true)]
        public async Task<ActionResult<UserDto>> Create([FromBody] UserDto dto)
        {
            var user = await userService.CreateUser(dto, CurrentUser);
            return CreatedAtAction("GetOne", new { id = user.UserId }, user);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        [HttpPut("{id}")]
        [Log("修改用户", OperateType.Update)]
        public async Task<ActionResult> Update(int id, [FromBody] UserDto dto)
        {
            if (id != dto.UserId)
            {
                return WarningMessage("要更新的数据和ID不匹配");
            }
            await userService.UpdateUser(dto, CurrentUser);
            return NoContent();
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpDelete]
        [Authorize(Roles = AppConstants.SUPER_ADMIN)]
        [Log("删除用户", OperateType.Delete)]
        public async Task<ActionResult> Delete([FromQuery] int[] ids)
        {
            await userService.DeleteByIds(ids, CurrentUser);
            return NoContent();
        }
        #endregion

        #region 用户中心
        /// <summary>
        /// 查询用户信息
        /// </summary>
        [HttpGet("uc-data")]
        public async Task<IActionResult> GetUserData()
        {
            var userId = CurrentUser.GetUserData().UserId;
            var dto = await userService.GetUserCenterData(userId);
            return Ok(dto);
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        [HttpPut("uc-data")]
        [Log("用户中心-修改信息", OperateType.Update)]
        public async Task UpdateUserData([FromBody] UserDataDto dto)
        {
            var userId = CurrentUser.GetUserData().UserId;
            if (dto.UserId != 0 && dto.UserId != userId)
            {
                throw new MessageException("只能本人操作");
            }
            dto.UserId = userId;
            await userService.UpdateUserData(dto, CurrentUser);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        [HttpPut("uc-pwd")]
        [Log("用户中心-修改密码", OperateType.Update)]
        public async Task UpdatePassword([FromBody] PwdDto dto)
        {
            var userId = CurrentUser.GetUserData().UserId;
            if ((dto.UserId ?? 0) != 0 && dto.UserId != userId)
            {
                throw new MessageException("只能本人操作");
            }
            var user = CurrentUser;
            await userService.UpdatePassword(userId, dto.OldPwd, dto.NewPwd, user);
        }
        #endregion
    }

    public class PwdDto
    {
        [Required(ErrorMessage = "原密码不能为空")]
        public string OldPwd { get; set; } = string.Empty;

        [Required(ErrorMessage = "新密码不能为空")]
        public string NewPwd { get; set; } = string.Empty;

        public int? UserId { get; set; }
    }
}
